/*
 * Copyright 2006 Robert Burrell Donkin
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ 
package rat.element;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.Locale;

import rat.document.IDocumentCollection;
import rat.document.impl.zip.ZipDocumentFactory;
import rat.document.report.IDocumentReporter;

public class ArchiveElement extends AbstractElement {

    private static final String[] ARCHIVE_EXTENSIONS = {
        "jar", "gz",
        "zip", "tar",
        "bz", "bz2",
        "rar", "war",
    };

	public ArchiveElement(File file) {
		super(file);
	}

    public ArchiveElement(String name, Reader reader) {
        super(name, reader);
    }

    public void report(IDocumentReporter report) {
        final String archiveName = getName();
        try {
        final IDocumentCollection documentCollection = read();
            report.reportOn(archiveName, documentCollection);
        } catch (Exception e) {
            report.reportOn(archiveName, e);
        }
    }
    
    /**
     * Reads the archive's contents.
     * @return <code>IDocumentCollection</code> 
     * or null if the archive cannot be read
     * @throws IOException 
     */
    public IDocumentCollection read() throws IOException {
        IDocumentCollection result = null;
        final String filename = getName();
        if (filename.endsWith(".zip") || filename.endsWith(".jar")) {
            result = ZipDocumentFactory.load(file);
        }
        return result;
    }
    
	public void accept(IElementVisitor visitor) {
		visitor.visit(this);
	}

	public String toString() {
		return "  A      " + getName();
	}

    /**
     * Is a file by that name an archive?
     */
    public static final boolean isArchive(final String name) {
        if (name == null) {return false;}
        String nameToLower = name.toLowerCase(Locale.US);
        boolean result = false;
        for (int i = 0; !result && i < ARCHIVE_EXTENSIONS.length; i++) {
            result = nameToLower.endsWith("." + ARCHIVE_EXTENSIONS[i]);
        }
        return result;
    }
	
}
